<?php
namespace App\Http\Controllers\H5;
use App\Enums\CouponStatus;
use App\Http\Controllers\Controller;
use App\Jobs\CouponChange;
use App\Models\NsSupplierGoods;
use App\Models\NsSupplierGoodsCoupon;
use App\Models\NsSupplierGoodsCouponRecord;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CouponController extends Controller
{

    public function __construct()
    {
        $this->middleware('throttle:10,1')->only('couponImport');
    }

    public function createCoupon(Request $request)
    {
        $validated = $request->validate([
            'price' => 'required|numeric|min:0.01',
            'num' => 'required|integer|min:1|max:10000',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'gid' => 'required|integer',
            'goods_name' => 'required|string|max:255',
            'merchant_number' => 'required|string|max:50',
        ]);

        $now = Carbon::now();
        $startTime = Carbon::parse($validated['start_time']);
        $endTime = Carbon::parse($validated['end_time']);

        // 状态判断逻辑优化
        $status = $now->lt($startTime) ? CouponStatus::PENDING : CouponStatus::ACTIVE;
        $delayTime = ($status === CouponStatus::PENDING)
            ? $now->diffInSeconds($startTime)
            : $now->diffInSeconds($endTime);

        // 准备记录数据
        $recordData = [
            'gid' => $validated['gid'],
            'goods_name' => $validated['goods_name'],
            'merchant_number' => $validated['merchant_number'],
            'price' => $validated['price'],
            'num' => $validated['num'],
            'starttime' => $startTime->timestamp,
            'endtime' => $endTime->timestamp,
            'created_at' => $now,
        ];

        DB::beginTransaction();

        try {
            // 插入记录表
            $recordId = NsSupplierGoodsCouponRecord::insertGetId($recordData);

            // 批量生成优惠券
            $coupons = [];
            $couponBase = [
                'gid' => $validated['gid'],
                'merchant_number' => $validated['merchant_number'],
                'price' => $validated['price'],
                'created_at' => $now,
                'record_id' => $recordId,
                'starttime' => $validated['start_time'],
                'endtime' => $validated['end_time'],
                'state' => $status,
            ];

            for ($i = 0; $i < $validated['num']; $i++) {
                $coupons[] = array_merge($couponBase, [
                    'coupon' => Str::uuid()->toString(),
                ]);
            }

            // 批量插入
            NsSupplierGoodsCoupon::insert($coupons);

            DB::commit();

            // 分发延迟任务
            CouponChange::dispatch($recordId,$status,$endTime->timestamp)
                ->delay(now()->addSeconds($delayTime))
                ->onConnection('redis')
                ->onQueue('CouponStatusChange')
                ->afterCommit();

            return successly();

        } catch (\Exception $e) {
            DB::rollBack();
            logger()->error('优惠券创建失败: ' . $e->getMessage());
            return fails('优惠券创建失败，请重试');
        }
    }
    public function recordList(Request $request)
    {
        $validated = $request->validate([
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date|after_or_equal:start_time',
            'goods_name' => 'nullable|string',
            'gid' => 'nullable|int',
            'merchant_number' => 'required'
        ]);

        $query = NsSupplierGoodsCouponRecord::query() ->where('merchant_number',$validated['merchant_number']);

        if (!empty($validated['start_time']) && !empty($validated['end_time'])) {
            $query->whereBetween('created_at', [
                $validated['start_time'],
                $validated['end_time']
            ]);
        }
        if(!empty($validated['goods_name'])){
            $query->where('goods_name','like','%'.$validated['goods_name'].'%');
        }
        if(!empty($validated['gid'])){
            $query->where('gid',$validated['gid']);
        }
        $list = $query->orderByDesc('created_at')->paginate(10);
        return successly($list);
    }

    public function couponList(Request $request)
    {
        $validated = $request->validate([
            'record_id' => 'required|integer',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date|after_or_equal:start_time',
            'u_start_time' => 'nullable|date',
            'u_end_time' => 'nullable|date|after_or_equal:u_start_time',
            'coupon' => 'nullable|string|max:36',
            'state' => 'nullable|integer|between:1,4',
        ]);

        $query = NsSupplierGoodsCoupon::where('record_id', $validated['record_id']);

        $this->applyCouponFilters($query, $validated);

        $list = $query->orderByDesc('created_at')->paginate(10);
        return successly($list);
    }

    public function couponConsume(Request $request)
    {
        $validated = $request->validate([
            'record_id' => 'required|integer',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date|after_or_equal:start_time',
            'u_start_time' => 'nullable|date',
            'u_end_time' => 'nullable|date|after_or_equal:u_start_time',
            'coupon' => 'nullable|string|max:36',
            'state' => 'nullable|integer|between:1,4',
        ]);

        $query = NsSupplierGoodsCoupon::where('record_id', $validated['record_id']);
        $this->applyCouponFilters($query, $validated);
        $stats = $query->selectRaw('
            COUNT(IF(state = 2, 1, NULL)) AS unused_count,
            COUNT(IF(state = 3, 1, NULL)) AS used_count,
            COUNT(IF(state = 4, 1, NULL)) AS expired_count,
            SUM(IF(state = 2, price, 0)) AS unused_amount,
            SUM(IF(state = 3, price, 0)) AS used_amount,
            SUM(IF(state = 4, price, 0)) AS expired_amount
        ')->first();

        return successly([
            'unused' => ['count' => $stats->unused_count, 'amount' => $stats->unused_amount],
            'used' => ['count' => $stats->used_count, 'amount' => $stats->used_amount],
            'expired' => ['count' => $stats->expired_count, 'amount' => $stats->expired_amount],
        ]);
    }

    public function couponImport(Request $request)
    {
        $validated = $request->validate([
            'record_id' => 'required|integer',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date|after_or_equal:start_time',
            'u_start_time' => 'nullable|date',
            'u_end_time' => 'nullable|date|after_or_equal:u_start_time',
            'coupon' => 'nullable|string|max:36',
            'state' => 'nullable|integer|between:1,4',
        ]);
        $record = NsSupplierGoodsCouponRecord::query()->findOrFail($validated['record_id']);
        $query = NsSupplierGoodsCoupon::where('record_id', $validated['record_id']);
        $this->applyCouponFilters($query, $validated);

        // 获取统计数据
        $stats = $query->clone()->selectRaw('
        COUNT(IF(state = 2, 1, NULL)) AS unused_count,
        COUNT(IF(state = 3, 1, NULL)) AS used_count,
        COUNT(IF(state = 4, 1, NULL)) AS expired_count,
        SUM(IF(state = 2, price, 0)) AS unused_amount,
        SUM(IF(state = 3, price, 0)) AS used_amount,
        SUM(IF(state = 4, price, 0)) AS expired_amount
    ')->first();

        // 获取导出数据
        $coupons = $query->select([
            'coupon', 'price', 'starttime', 'endtime', 'use_time', 'state'
        ])->orderByDesc('created_at')->get();

        // 转换状态文本
        $coupons->transform(function ($item) {
            $item->state_text = CouponStatus::COUPON_STATUS_MAP[$item->state] ?? '未知状态';
            return $item;
        });

        // 准备统计信息
        $summary = [
            '已使用：' . $stats->used_count . '个 ' . number_format($stats->used_amount, 2) . '元',
            '未使用：' . $stats->unused_count . '个 ' . number_format($stats->unused_amount, 2) . '元',
            '已过期：' . $stats->expired_count . '个 ' . number_format($stats->expired_amount, 2) . '元'
        ];
        $allNum = $stats->used_count + $stats->unused_count + $stats->expired_count;
        // 导出
        $headers = [
            'coupon' => '券码',
            'price' => '金额',
            'starttime' => '有效期开始时间',
            'endtime' => '有效期结束时间',
            'use_time' => '使用时间',
            'state_text' => '券码状态'
        ];
        // 摘要信息
        $abstract = [
            '统计摘要',
            $record->goods_name,
            $allNum.'个优惠券'
        ];
        $this->exportToCsv($record->goods_name.'券码信息', $headers, $coupons->toArray(), $summary,$abstract);
    }

    /**
     * 应用优惠券查询过滤器
     */
    private function applyCouponFilters($query, array $filters)
    {
        if (!empty($filters['start_time']) && !empty($filters['end_time'])) {
            $query->whereBetween('created_at', [
                $filters['start_time'],
                $filters['end_time']
            ]);
        }

        if (!empty($filters['u_start_time']) && !empty($filters['u_end_time'])) {
            $query->whereBetween('use_time', [
                $filters['u_start_time'],
                $filters['u_end_time']
            ]);
        }

        if (!empty($filters['coupon'])) {
            $query->where('coupon', $filters['coupon']);
        }

        if (!empty($filters['state'])) {
            $query->where('state', $filters['state']);
        }
    }

    /**
     * 导出CSV文件
     */
    private function exportToCsv(string $fileName, array $headers, array $data, array $summary = [],array $abstract=[])
    {
        $output = fopen('php://output', 'w');

        // 设置HTTP头
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $fileName . '.csv"');
        header('Cache-Control: max-age=0');

        // 添加摘要信息
        if (!empty($summary)) {
            fputcsv($output, $abstract);
            foreach ($summary as $line) {
                fputcsv($output, [$line]);
            }
            fputcsv($output, []); // 空行
        }

        // 添加表头
        fputcsv($output, array_values($headers));

        // 添加数据
        foreach ($data as $row) {
            // 按表头顺序提取数据
            $csvRow = [];
            foreach (array_keys($headers) as $field) {
                $csvRow[] = $row[$field] ?? '';
            }
            fputcsv($output, $csvRow);
        }

        fclose($output);
        exit;
    }

    public function couponInfo(Request $request)
    {
        $validated = $request->validate([
            'coupon' => 'required|string|max:36',
            'gid' => 'required|integer'
        ]);

        $coupon = NsSupplierGoodsCoupon::where('coupon', $validated['coupon'])->where('gid',$validated['gid'])
            ->where('state', 2) // 未使用
            ->first();

        if (!$coupon) {
            return fails('经验测无效优惠码，请重新输入');
        }

        $goods = NsSupplierGoods::find($validated['gid'], ['price', 'profit', 'profit']);

        if (!$goods) {
            return fails('商品不存在');
        }

        $totalPrice = $goods->price + $goods->profit;

        if ($coupon->price > $totalPrice) {
            return fails('优惠码金额不能大于原价，请重新输入');
        }

        if ($coupon->price == $totalPrice) {
            return fails('优惠码金额不能等于原价，请重新输入');
        }

        return successly($coupon);
    }

}
